package main.interaction
{
	import away3d.core.base.Face;
	import away3d.core.base.Mesh;
	import away3d.core.base.Object3D;
	import away3d.events.MouseEvent3D;
	import away3d.materials.BitmapMaterial;
	
	import flash.events.EventDispatcher;
	import flash.geom.ColorTransform;
	
	[Event(type="main.StateEvent", name="mouseOver")]
	[Event(type="main.StateEvent", name="mouseOut")]
	[Event(type="main.StateEvent", name="mouseUp")]
	public class InteractiveObject extends EventDispatcher
	{
		
		public var overColor:ColorTransform = new ColorTransform(2,2,2);
		private static var outColor:ColorTransform = new ColorTransform();
		
		
		public var objectName:String;
		public var object:Object3D;
		public var targetState:String;
		public var regions:Array = [];
		public var label:String;
		private var interactiveObjects:Array = [];	
		private var _enabled:Boolean = false;
		
		public function InteractiveObject() {
		}
		
		public function set enabled(b:Boolean):void {
			if (b) {
				object.addOnMouseOver(onMouseOver);
				object.addOnMouseOut(onMouseOut);
				object.addOnMouseUp(onMouseUp);
			} else {
				object.removeOnMouseOver(onMouseOver);
				object.removeOnMouseOut(onMouseOut);
				object.removeOnMouseUp(onMouseUp);
				onMouseOut();
			}
			object.useHandCursor = b;
			_enabled = b;
		}
		
		public function get enabled():Boolean {
			return _enabled;
		}
		
		private function onMouseOver(e:MouseEvent3D):void {
			var ev:StateEvent = new StateEvent(StateEvent.MOUSE_OVER);
			ev.interactiveObject = this;
			for each(var f:Face in Mesh(object).faces) {
				BitmapMaterial(f.material).colorTransform = overColor;
			}
			dispatchEvent(ev);
		}
		
		private function onMouseOut(e:MouseEvent3D = null):void {
			var ev:StateEvent = new StateEvent(StateEvent.MOUSE_OUT);
			ev.interactiveObject = this;
			for each(var f:Face in Mesh(object).faces) {
				BitmapMaterial(f.material).colorTransform = outColor;
			}
			dispatchEvent(ev);
		}
		
		private function onMouseUp(e:MouseEvent3D):void {
			var ev:StateEvent = new StateEvent(StateEvent.MOUSE_UP);
			ev.interactiveObject = this;
			dispatchEvent(ev);
		}
		
		
		public static function fromXML(xml:XML):InteractiveObject {
			var iob:InteractiveObject = new InteractiveObject();
			iob.objectName = xml.@object;
			iob.targetState = xml.@targetState;
			
			if (xml.@label) iob.label = xml.@label;
			return iob;
		}

	}
}